home *** CD-ROM | disk | FTP | other *** search
- Path: locutus.rchland.ibm.com!usenet
- From: pstaite@vnet.ibm.com
- Newsgroups: comp.lang.c++
- Subject: Re: Derivation and protected members
- Date: 31 Jan 1996 15:58:40 GMT
- Organization: IBM OS/2 Device Driver Development Rochester, MN
- Message-ID: <4eo3jg$qqc@locutus.rchland.ibm.com>
- References: <4el84h$t86@beavis.kronos.com>
- Reply-To: pstaite@vnet.ibm.com
- NNTP-Posting-Host: warpone.rchland.ibm.com
- X-Newsreader: IBM NewsReader/2 v1.2
-
- In <4el84h$t86@beavis.kronos.com>, lipsett@kronos.com (Roger Lipsett) writes:
- >Suppose I have a base class, bas, and a derived class, der, of which bas is a
- >public base. der has additional data members beyond those provided by bas. All
- >data members of both classes are protected.
- >
- >I wish to define an operation (=) that will assign an instance of bas to an
- >instance of der by setting all of der's data members that are inherited from
- >bas to the values as provided by the instance of bas, and leaving untouched
- >the other data members of der..
- >
- >There appears to be no simple way to do this. The der-instance does not have
- >access to the protected members of the bas-instance, as those members are
- >protected. What am I missing here?
-
- Why not let the bas class' operator=() do the work for you? Seems you
- really just want to assign the bas object to the bas portion of a der
- object. Something like:
-
- #include<iostream.h>
-
- class bas {
- public:
- bas( int x = 0, int y = 0 ) : n( x ), m( y ) {}
- virtual ~bas() {}
- bas& operator=( const bas& );
- virtual void print() const { cout << "bas: " << n << ' ' << m << endl; }
- protected:
- int n,
- m;
- };
-
- bas& bas::operator=( const bas& b ) {
- n = b.n;
- m = b.m;
- return *this; }
-
-
- class der : public bas {
- public:
- der( int x = 1, int y = 2 ) : bas( x, y ), z( 0 ) {}
- der& operator=( const bas& );
- virtual void print() const { bas::print(); cout << "der: " << z << endl; }
- protected:
- int z;
- };
-
- der& der::operator=( const bas& b ) {
- bas::operator=( b );
- return *this; }
-
-
- int main() {
- bas b( 8, 16 );
- der d( 4, 12 );
- d = b;
- d.print();
- return 0; }
-
-
- You should even be able to make bas::operator=() protected if you want
- to restrict access.
-
-
-
- Phil Staite, team OS/2
- internet: pstaite@vnet.ibm.com internal: pstaite@rchland
-
-